/**
 * @author: Miss.杨
 * @date: 2024年12月29日 21:36:30
 * @description: 
 */
package com.sheepone.monitor.client;

import java.net.InetSocketAddress;

import com.sheepone.monitor.client.config.MonitorClientConfig;
import com.sheepone.monitor.runner.AbstractMonitorRunner;
import com.sheepone.monitor.runner.listener.MonitorRunnerListenerAdapter;
import com.sheepone.webdev.log.WebDevLogger;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author: Miss.杨
 * @date: 2024年12月29日 21:36:30
 * @description: 基础的ClientRunner
 *               1、关注MonitorClientConfig的配置解析
 *               2、关注连接建立流程
 */
public class MonitorClientRunner<C extends MonitorClientConfig, I extends AbstractMonitorClientChannelInitializer>
        extends AbstractMonitorRunner<C, I> {
    private static WebDevLogger logger = WebDevLogger.getLogger(MonitorClientRunner.class);

    public MonitorClientRunner(C config) {
        super(config);
    }

    private NioEventLoopGroup group;

    protected void shutdown() {
        group.shutdownGracefully();
    }

    @Override
    public void beforeStart() {
        group = new NioEventLoopGroup(config.getThreads());
        addListener(new MonitorRunnerListenerAdapter() {
            @Override
            public void startSuccessfully(Channel channel) {
                logger.info("MonitorClient[{}] connect server {}:{} successfully", config.getName(),
                        config.getServerHostname(), config.getServerPort());
            }
        });
    }

    protected ChannelFuture start(I channelInitializer) throws Exception {
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(channelInitializer);
        return bootstrap
                .connect(new InetSocketAddress(config.getServerHostname(), config.getServerPort())).sync();
    }
}